﻿using UnityEngine;
using UnityEngine.Rendering;
using UnityEngine.UI;

namespace CGF
{
    public static class UILayerHelper
    {
        public static void SetSortingOrder(Transform target, int sortingOrder)
        {
            SetChildrenSortingOrder(target, "Default", ref sortingOrder);
        }

        public static void SetChildrenSortingOrder(Transform node, string layerName, ref int order)
        {
            Canvas canvas = node.GetComponent<Canvas>();
            if (canvas)
            {
                canvas.overrideSorting = true;
                canvas.sortingLayerName = layerName;
                canvas.sortingOrder = order;
                order++;
                GraphicRaycaster raycaster = node.GetComponent<GraphicRaycaster>();
                if (!raycaster) node.gameObject.AddComponent<GraphicRaycaster>();
            }
            else
            {
                //内部很多ParticleSystem的，可手动用SortingGroup组件包住
                SortingGroup sortingGroup = node.GetComponent<SortingGroup>();
                if (sortingGroup)
                {
                    sortingGroup.sortingLayerName = layerName;
                    sortingGroup.sortingOrder = order;
                    order++;

                    //如果发现被手动包了 SortingGroup 组件，则无需再遍历子节点，直接return
                    return;
                }

                ParticleSystem particle = node.GetComponent<ParticleSystem>();
                if (particle)
                {
                    ParticleSystem[] particles = node.GetComponentsInChildren<ParticleSystem>(true);
                    for (int i = 0; i < particles.Length; i++)
                    {
                        Renderer renderer = particles[i].GetComponent<Renderer>();
                        renderer.sortingLayerName = layerName;
                        renderer.sortingOrder = order;
                        order++;
                    }

                    //如果发现ParticleSystem，也直接一次性处理所有子特效，无需再遍历子节点
                    return;
                }
            }

            //继续处理子节点
            for (int i = 0; i < node.childCount; i++)
            {
                SetChildrenSortingOrder(node.GetChild(i), layerName, ref order);
            }
        }
    }
}